package com.icodingedu.springcloud.controller;

import com.icodingedu.springcloud.entity.Account;
import com.icodingedu.springcloud.entity.AuthResponse;
import com.icodingedu.springcloud.entity.ResponseCode;
import com.icodingedu.springcloud.service.AuthService;
import com.icodingedu.springcloud.service.JwtService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@Slf4j
@RestController
public class JwtController implements AuthService {

    @Autowired
    private JwtService jwtService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public AuthResponse login(String username, String password) {
        Account account = Account.builder()
                .username(username)
                .build();
        //TODO 0-这一步需要进入数据库进行用户名和密码验证,假定验证通过
        // 1-生成token
        String token = jwtService.token(account);
        account.setToken(token);
        //保存refreshToken
        account.setRefreshToken(UUID.randomUUID().toString());
        // 2-将token和refreshToken关系保存到Redis
        redisTemplate.opsForValue().set(account.getRefreshToken(),account);
        // 3-返回token
        return AuthResponse.builder()
                .account(account)
                .code(ResponseCode.SUCCESS)
                .build();
    }

    @Override
    public AuthResponse verify(String token, String username) {
        boolean flag = jwtService.verify(token, username);

        return AuthResponse.builder()
                .code(flag?ResponseCode.SUCCESS:ResponseCode.INVALID_TOKEN)
                .build();
    }

    @Override
    public AuthResponse refresh(String refresh) {
        Account account = (Account) redisTemplate.opsForValue().get(refresh);
        if(account==null){
            return AuthResponse.builder()
                    .code(ResponseCode.USER_NOT_FOUNT)
                    .build();
        }
        //1-新生成一个token
        String token = jwtService.token(account);
        account.setToken(token);
        //2-更新refreshToken
        account.setRefreshToken(UUID.randomUUID().toString());
        //3-将原来的删除
        redisTemplate.delete(refresh);
        //4-添加新的token
        redisTemplate.opsForValue().set(account.getRefreshToken(),account);
        return AuthResponse.builder()
                .account(account)
                .code(ResponseCode.SUCCESS)
                .build();
    }
}
